from rest_framework import serializers
from users.models import User


class UserSerilaizer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email')


class UserAddSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'
        extra_kwargs = {
            'password': {
                'min_length': 8,
                'max_length': 20,
                'write_only': True
            },
            'username': {
                'min_length': 5,
                'max_length': 20
            }
        }

    # 重写序列化中的create方法
    def create(self, validated_data):
        # 保存用户数据并对密码加密
        user = User.objects.create_user(**validated_data)
        return user
